/**
 * API测试脚本 (ES模块版本)
 */
import { fileURLToPath } from 'url';
import { dirname, join } from 'path';
import fs from 'fs';
import https from 'https';
import http from 'http';

// 获取当前文件目录
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);

// 加载配置
const configPath = join(__dirname, 'env.config');
let config = {};

try {
    const content = fs.readFileSync(configPath, 'utf8');
    content.split('\n').forEach(line => {
        if (line.trim().startsWith('#') || !line.trim()) return;

        const match = line.match(/^([A-Z0-9_]+)="([^"]*)"/);
        if (match) {
            const [, key, value] = match;
            config[key] = value;
        }
    });

    console.log('配置加载成功:');
    console.log(`- API基础URL: ${config.AUTO_API_BASE_URL}`);
    console.log(`- 项目ID: ${config.PROJECT_ID}`);
    console.log(`- Schema名称: ${config.SCHEMA_NAME}`);
} catch (error) {
    console.error('加载配置文件失败:', error);
    process.exit(1);
}

/**
 * 发送HTTP请求
 */
async function sendRequest(url, method = 'GET', body = null, headers = {}) {
    return new Promise((resolve, reject) => {
        try {
            const requestUrl = new URL(url);
            const options = {
                hostname: requestUrl.hostname,
                port: requestUrl.port || (requestUrl.protocol === 'https:' ? 443 : 80),
                path: requestUrl.pathname + requestUrl.search,
                method: method,
                headers: {
                    'Content-Type': 'application/json',
                    ...headers
                }
            };

            console.log(`发送${method}请求到: ${url}`);

            const req = (requestUrl.protocol === 'https:' ? https : http).request(options, (res) => {
                let data = '';

                res.on('data', (chunk) => {
                    data += chunk;
                });

                res.on('end', () => {
                    let responseData;

                    try {
                        responseData = data ? JSON.parse(data) : {};
                    } catch (error) {
                        responseData = {
                            rawData: data,
                            parseError: error.message
                        };
                    }

                    if (res.statusCode >= 200 && res.statusCode < 300) {
                        console.log(`✅ 响应成功 (${res.statusCode})`);
                        resolve({
                            statusCode: res.statusCode,
                            headers: res.headers,
                            data: responseData
                        });
                    } else {
                        console.error(`❌ 响应失败 (${res.statusCode})`);
                        reject({
                            statusCode: res.statusCode,
                            headers: res.headers,
                            data: responseData,
                            message: `HTTP错误: ${res.statusCode}`
                        });
                    }
                });
            });

            req.on('error', (error) => {
                console.error(`❌ 请求错误: ${error.message}`);
                reject({
                    message: `请求错误: ${error.message}`,
                    error
                });
            });

            if (body) {
                req.write(typeof body === 'string' ? body : JSON.stringify(body));
            }

            req.end();
        } catch (error) {
            console.error('请求构建失败:', error);
            reject(error);
        }
    });
}

// 测试API连接
async function testConnection() {
    try {
        console.log('\n🔍 测试API连接...');

        // 测试Ping端点
        const pingUrl = `${config.AUTO_API_BASE_URL}/ping`;
        try {
            const pingResponse = await sendRequest(pingUrl);
            console.log('✅ Ping测试成功:', pingResponse.data);
        } catch (error) {
            console.log('⚠️ Ping失败，尝试其他端点...');
        }

        // 尝试获取表列表
        const tablesUrl = `${config.AUTO_API_BASE_URL}/tables?projectId=${config.PROJECT_ID}&schema=${config.SCHEMA_NAME}`;
        try {
            const tablesResponse = await sendRequest(tablesUrl);
            console.log('✅ 获取表列表成功');

            // 显示表数量
            if (tablesResponse.data && Array.isArray(tablesResponse.data.tables)) {
                console.log(`📊 找到 ${tablesResponse.data.tables.length} 张表`);
                console.log('表列表示例 (最多5张):');
                tablesResponse.data.tables.slice(0, 5).forEach(table => {
                    console.log(`- ${table}`);
                });
            } else {
                console.log('⚠️ 表数据格式未知:', tablesResponse.data);
            }
        } catch (error) {
            console.error('❌ 获取表列表失败:', error.message);
            if (error.data) {
                console.error('错误详情:', error.data);
            }
        }

        console.log('\n🏁 API测试完成');
    } catch (error) {
        console.error('❌ 测试过程发生错误:', error);
    }
}

// 执行测试
testConnection(); 